package com.zhoug.zmui.dialog.menu;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ListView;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;
import com.zhoug.common.adapters.BaseListViewAdapter;
import com.zhoug.common.adapters.recycler.BaseRecyclerViewAdapter;
import com.zhoug.common.adapters.recycler.BaseViewHolder;
import com.zhoug.common.utils.LogUtils;
import com.zhoug.common.utils.ResourceUtils;
import com.zhoug.zmui.R;
import com.zhoug.zmui.ZMUIAnimations;
import com.zhoug.zmui.dialog.ZMUIBaseDialog;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 多级菜单
 */
public class ZMUIMenuDialog extends ZMUIBaseDialog implements TabLayout.OnTabSelectedListener {
    private static final String TAG = ">>>ZMUIMenuDialog";
    private static final boolean DEBUG=true;
    private TabLayout mTabLayout;
    private ListView mListView;
    private List<? extends Menu> menus;
    private MenuAdapter mAdapter;
    private Callback mCallback;
    private int selectColor=Color.parseColor("#22adff");

    public ZMUIMenuDialog(@NonNull Context context) {
        this(context,0);
    }

    public ZMUIMenuDialog(@NonNull Context context, List<? extends Menu> menus) {
        this(context,0);
        this.menus=menus;
    }

    public ZMUIMenuDialog(@NonNull Context context, int themeResId) {
        this(context, themeResId,0,0);
    }

    public ZMUIMenuDialog(@NonNull Context context, int themeResId, int defStyleAttr, int defStyleRes) {
        super(context, themeResId, defStyleAttr, defStyleRes);
    }

    @Override
    protected void initialize(@NonNull Context context, int defStyleAttr, int defStyleRes) {
        super.initialize(context, defStyleAttr, defStyleRes);
        setWindowAnimations(ZMUIAnimations.ANIM_DOWN);
        setAttributes(WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.WRAP_CONTENT,Gravity.BOTTOM);
        setFullWidth(true);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.zmui_menu_dialog;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setCanceledOnTouchOutside(true);
        mTabLayout=findViewById(R.id.tabLayout_menuView);
        mListView=findViewById(R.id.listView);

        //设置分割线
        ColorDrawable colorDrawable=new ColorDrawable();
        colorDrawable.setColor(Color.parseColor("#cccccc"));
        mListView.setDivider(colorDrawable);
        mListView.setDividerHeight(ResourceUtils.dpTopx(1));

        mAdapter = new MenuAdapter();
        mAdapter.setData(menus);
        mListView.setAdapter(mAdapter);
        addTab(menus);
        mTabLayout.addOnTabSelectedListener(this);
    }

    private void addTab(List<? extends Menu> menus){
        if(menus==null)return;
        for(Menu menu1:menus){
            if(menu1!=null){
                menu1.setSelected(false);
            }
        }
        mTabLayout.addTab(mTabLayout.newTab().setText("请选择").setTag(menus));
    }

    /**
     * 移除指定位置后面的tab
     * @param position
     */
    private void removeTabLater(int position){
        int tabCount = mTabLayout.getTabCount();
        if (DEBUG) {
            Log.d(TAG, "removeTabLater: position="+position);
            Log.d(TAG, "removeTabLater: tabCount="+tabCount);
        }

       for(int i=tabCount-1;i>position;i--){
           mTabLayout.removeTabAt(i);
       }

    }

    /**
     * 选中指定位置的tab
     * @param position
     */
    private void select(int position){
        TabLayout.Tab tabAt = mTabLayout.getTabAt(position);
        if(tabAt!=null){
            tabAt.select();
        }
    }

    private class MenuAdapter<T extends Menu> extends BaseListViewAdapter<T> implements View.OnClickListener{

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if(convertView ==null){
                convertView= LayoutInflater.from(getContext()).inflate(R.layout.zmui_menu_dialog_item,null);
            }
            TextView textView=convertView.findViewById(R.id.menu_view_item);
            List<T> data = getData();
            T t = data.get(position);
            if(t!=null){
                textView.setText( t.getName());
                convertView.setTag(t);
                if(t.isSelected()){
                    textView.setTextColor(selectColor);
                }else{
                    textView.setTextColor(Color.BLACK);
                }
                convertView.setClickable(true);
                convertView.setOnClickListener(MenuAdapter.this);
            }
            return convertView;
        }

        @Override
        public void onClick(View v) {
            Menu menu= (Menu) v.getTag();
            //清空选中状态
            List<Menu> data = mAdapter.getData();
            for(Menu menu1:data){
                menu1.setSelected(false);
            }
            //设为选中
            menu.setSelected(true);
            //选中后改变颜色


            //当前选择的tab名字修改为选择的菜单name
            int selectedTabPosition = mTabLayout.getSelectedTabPosition();
            TabLayout.Tab tabAt = mTabLayout.getTabAt(selectedTabPosition);
            if(tabAt!=null){
                tabAt.setText(menu.getName());
            }
            //如果后面的子菜单tab显示了,先移除后面的
            removeTabLater(selectedTabPosition);
            List<? extends Menu> child = menu.getChild();
            if(child ==null || child.size()==0){
//                Toast.makeText(getContext(),menu.getName() , Toast.LENGTH_SHORT).show();
                dismiss();
                if(mCallback!=null){
                    mCallback.onSelected(menu);
                }
            }else{
                //有子菜单,显示子菜单
                addTab(child);
                select(selectedTabPosition+1);
                mAdapter.setData(child);
            }

            mAdapter.notifyDataSetChanged();
        }
    }




    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        if (DEBUG) {
            Log.d(TAG, "onTabSelected: tab="+tab.getText());

        }
        List<Menu> list = (List<Menu>) tab.getTag();
        if(list==null)return;
        mAdapter.setData(list);
        mAdapter.notifyDataSetChanged();
        boolean hasSelect=false;
        for(int i = 0;i<list.size();i++){
            Menu menu = list.get(i);
            if(menu.isSelected()){
                hasSelect=true;
                scrollTo(i);
                break;
            }
        }
        if(!hasSelect){
            scrollTo(0);
        }
    }

    private void scrollTo(int position){
        if (mListView != null && getMenus() != null && getMenus().size() > 0) {
            Log.d(TAG, "initListView:设置选中位置:" + position);
            if (position >= 0 && position < getMenus().size()) {
                mListView.setSelection(position);
            } else {
                mListView.setSelection(0);
            }
        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
        if (DEBUG) {
            Log.d(TAG, "onTabUnselected: tab="+tab.getText());

        }
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
        if (DEBUG) {
            Log.d(TAG, "onTabReselected: tab="+tab.getText());

        }
    }


    public void setSelectColor(int selectColor) {
        this.selectColor = selectColor;
    }

    public List<? extends Menu> getMenus() {
        return menus;
    }

    public void  setMenus(List<? extends Menu> menus) {
        this.menus = menus;
    }

    public void updateMenu(List<? extends Menu> menus){
        this.menus = menus;
        if(mTabLayout!=null){
            mTabLayout.removeAllTabs();
            addTab( this.menus);
        }
        if(mAdapter!=null){
            mAdapter.setData( this.menus);
            mAdapter.notifyDataSetChanged();
        }
    }

    public void notifyDataSetChanged(){
        if(mAdapter!=null){
            mAdapter.notifyDataSetChanged();
        }
    }

    public Callback getCallback() {
        return mCallback;
    }

    public void setCallback(Callback callback) {
        this.mCallback = callback;
    }

    public  interface Callback{
        void onSelected(Menu menu);

    }
}
